package com.zhang.flink;

/**
 * @author Alger
 * @date 2021/11/12  15:16
 */

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * 批处理
 */
public class WordCount {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //读取文件得到数据集
        DataSource<String> stringDataSource = env.readTextFile("E:\\workspace\\jqyh\\flink_test\\src\\main\\resources\\hello.txt");

        //对数据集进行处理,按空格分开，输出为（word，1）二元组
        AggregateOperator<Tuple2<String, Integer>> wordCountDataSet = stringDataSource.flatMap(new MyFlatMapper()).groupBy(0).sum(1);
        wordCountDataSet.print();


    }

    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] words = value.split(" ");

            for (String word : words) {
                out.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
